import paramiko  
 
from .exception import JobError 
  
def ssh_execute_command(hostname: str, username: str, password: str, command: str) -> str:  
    try:  
        # 创建一个SSH客户端  
        ssh_client = paramiko.SSHClient()  
        # 自动添加策略，保存服务器的主机名和密钥信息，不检查HostKey  
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
        # 连接到服务器  
        ssh_client.connect(hostname, username=username, password=password)  
          
        # 执行命令  
        _, stdout, stderr = ssh_client.exec_command(command)  
          
        # 关闭SSH连接  
        ssh_client.close()

        # 获取命令执行结果  
        output = stdout.read().decode()  
        error = stderr.read().decode()  
        print(f"Output: {output}")  
        if error:  
            print(f"Error: {error}")  
            raise JobError("exec_command return error message")
        return output
    except Exception as e:  
        print(f"An error occurred: {repr(e)}")
        raise JobError(repr(e))
     
